package com.ruoyi.stock2.controller;

import java.io.*;
import java.util.List;
import java.util.StringJoiner;

import com.ruoyi.common.utils.StringUtils;
import org.apache.commons.io.FileUtils;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.stock2.domain.WEBWORD;
import com.ruoyi.stock2.service.IWEBWORDService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;
import fr.opensagres.poi.xwpf.converter.core.BasicURIResolver;
import fr.opensagres.poi.xwpf.converter.core.FileImageExtractor;
import fr.opensagres.poi.xwpf.converter.xhtml.XHTMLConverter;
import fr.opensagres.poi.xwpf.converter.xhtml.XHTMLOptions;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

/**
 * webwordController
 * 
 * @author ruoyi
 * @date 2019-12-19
 */
@Controller
@RequestMapping("/stock2/WEBWORD")
public class WEBWORDController extends BaseController
{
    private String prefix = "stock2/WEBWORD";

    @Autowired
    private IWEBWORDService wEBWORDService;

    @RequiresPermissions("stock2:WEBWORD:view")
    @GetMapping()
    public String WEBWORD()
    {
        return prefix + "/WEBWORD";
    }

    /**
     * 查询webword列表
     */
    @RequiresPermissions("stock2:WEBWORD:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(WEBWORD wEBWORD)
    {
        startPage();
        List<WEBWORD> list = wEBWORDService.selectWEBWORDList(wEBWORD);
        return getDataTable(list);
    }

    /**
     * 导出webword列表
     */
    @RequiresPermissions("stock2:WEBWORD:export")
    @Log(title = "webword", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(WEBWORD wEBWORD)
    {
        List<WEBWORD> list = wEBWORDService.selectWEBWORDList(wEBWORD);
        ExcelUtil<WEBWORD> util = new ExcelUtil<WEBWORD>(WEBWORD.class);
        return util.exportExcel(list, "WEBWORD");
    }

    /**
     * 新增webword
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存webword
     */
    @RequiresPermissions("stock2:WEBWORD:add")
    @Log(title = "webword", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(WEBWORD wEBWORD)
    {
        return toAjax(wEBWORDService.insertWEBWORD(wEBWORD));
    }

    @Log(title="word文件上传", businessType=BusinessType.INSERT)
    @PostMapping({"/add1"})
    @ResponseBody
    public AjaxResult addSave1(@RequestParam("upload") MultipartFile upload, String fileName) {
        String os = System.getProperty("os.name");
        String urlPre = "/profile/upload/summernote-develop/doc2html/";
        if(os.toLowerCase().startsWith("win")){
            urlPre = "f:"+urlPre;
        }

        String[] fileNames = fileName.split("\\.");

        int sizef = fileNames.length;
        String newfileName = fileNames[(sizef - 2)] + ".html";
        String newfileName2 = fileNames[(sizef - 2)] + "-v1.html";
        try
        {
            long al = System.currentTimeMillis();
            File imgf = new File(urlPre + fileName);
            upload.transferTo(imgf);
            while (!imgf.exists()) {
                try {
                    Thread.sleep(100L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            long bl = System.currentTimeMillis();
            //读取并转换成html
            docxToHtml(urlPre+fileName,urlPre + newfileName, urlPre);
            long cl = System.currentTimeMillis();
            //读取并修改加入javascript
            File input = new File(urlPre + newfileName);
            Document doc = Jsoup.parse(input, "UTF-8", "http://example.com/");

            Elements heads = doc.getElementsByTag("head");
            if(!heads.isEmpty()){
                Element e = heads.get(0);
                e.append("<title>"+newfileName2+"</title>");
                e.prepend("<meta http-equiv=Content-Type  content=\"text/html; charset=utf-8\" >");
               // e.appendChild()
                String a =
                        "<link rel=\"stylesheet\" href=\"../bootstrap.3.3.5.css\" /> \n"+
                        "<link href=\"../dist/summernote.css\" rel=\"stylesheet\"> \n"+
                        "<script src=\"../jquery.3.2.1.js\" /> \n"+
                        "<script type=\"text/javascript\" src=\"../bootstrap.3.3.5.js\" /> \n"+
                        "<script src=\"../dist/summernote.js\" />\n"+
                        "<script src=\"../dist/lang/summernote-zh-CN.js\" />\n"+
                        "<script src=\"../doc2html.js\" /> \n";
                e.append(a);

            }
            Elements bodys = doc.getElementsByTag("body");

            if(!bodys.isEmpty()){
                Element e = bodys.get(0);
                e.addClass("container");
                String body_divs = e.html();
                e.html("");

                e.append("<div class='summernote'>"+body_divs+"</div>");
                e.prepend( "<div class=\"ibox-title\" id=\"edit_save\"></div>");
//                        "<button id=\"edit\" class=\"btn btn-primary btn-xs m-l-sm\" onclick=\"edit()\" type=\"button\">编辑</button>"+
//                        "<button id=\"save\" class=\"btn btn-primary  btn-xs\" onclick=\"save()\" type=\"button\">保存</button>"+

            }

            File outputf = new File(urlPre + newfileName2);
            FileOutputStream fos = new FileOutputStream(outputf, false);
            OutputStreamWriter osw = new OutputStreamWriter(fos, "utf-8");
            osw.write("<!DOCTYPE html>\n"+doc.html());
            osw.close();

            long dl = System.currentTimeMillis();
            System.out.println(bl-al);
            System.out.println(cl-bl);
            System.out.println(dl-cl);
            WEBWORD webword = new WEBWORD();
            webword.setName(fileName);
            webword.setHtml("/profile/upload/summernote-develop/doc2html/"+newfileName2);
            return toAjax(wEBWORDService.insertWEBWORD(webword));
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return toAjax(0);
    }

    public static void main(String[] args) {
        WEBWORDController w = new WEBWORDController();
        try {
           // w.docxToHtml("E:\\羊羯子火锅.doc","f:/profile/upload/sample.html","f:/profile/upload/");
            w.doc2Html(new File("E:\\羊羯子火锅.doc"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String doc2Html(File docFile) {
        String htmlPath=docFile.getAbsolutePath().replaceAll(docFile.getName(),"")+docFile.getName().replaceAll(".doc",".html");

        String result = "";
        File htmlFile = new File(htmlPath);
        if(!docFile.exists()){
           // logger.error("{}.doc不存在",docFile.getName());
        }
        try{
            HWPFDocument wordDocument = new HWPFDocument(new POIFSFileSystem(docFile));
            org.w3c.dom.Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
            WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(document);
            //保存图片，并返回图片的相对路径
            wordToHtmlConverter.setPicturesManager((content, pictureType, name, width, height) -> {
                //图片byte[],图片type,图片名,图片宽度,图片高度
                //上传文件返回url  伪代码
                //String url =  FileUploadUtil.upload(fileByte, name, true);
                String url = "https://gss2.bdstatic.com/-fo3dSag_xI4khGkpoWK1HF6hhy/baike/w%3D268%3Bg%3D0/sign=bcd0f6384290f60304b09b410129d426/91ef76c6a7efce1bab44b2c3a751f3deb48f654f.jpg";

                String imagePath = "f:/profile/upload/image";
                return imagePath;
            });
            wordToHtmlConverter.processDocument(wordDocument);
            org.w3c.dom.Document htmlDocument = wordToHtmlConverter.getDocument();
            DOMSource domSource = new DOMSource(htmlDocument);
            StreamResult streamResult = new StreamResult();
            streamResult.setOutputStream(new FileOutputStream(htmlFile));
            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer serializer = tf.newTransformer();
            serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
            serializer.setOutputProperty(OutputKeys.INDENT, "yes");
            serializer.setOutputProperty(OutputKeys.METHOD, "html");
            serializer.transform(domSource, streamResult);
            result = FileUtils.readFileToString(htmlFile,"UTF-8");
            //这里拿到html文本后 jsoup 解析
            result =  processUeditorStyle(result);
        } catch (Exception e) {
            e.printStackTrace();
            //logger.error("doc--->html出错:{}",e.getMessage());
        }finally {
            htmlFile.delete();
        }
        return result;
    }

    /**
     *  处理 ueditor 样式
     * @param result
     * @return
     */
    private static String processUeditorStyle(String result) {
        Document doc = Jsoup.parse(result);
        //body 处理
        //<body class="view" contenteditable="true" spellcheck="false" style="overflow-y: hidden; height: 500px; cursor: text;">
        doc.body().attr("class","view").attr("contenteditable","true")
                .attr("spellcheck","false").attr("style","overflow-y: hidden; height: 500px; cursor: text;");
        //img处理
        Elements imgs = doc.select("img[src]");
        for (Element img : imgs) {
            String width = "";
            String[] styles = img.attr("style").split(";");
            if (styles.length>0){
                width = styles[0].split(":")[1].replaceAll("in","");
                if (Float.parseFloat(width) > 7.43f){
                    StringJoiner styleValue = new StringJoiner(";");
                    styleValue.add("width:173px");
                    for (int i = 1; i < styles.length; i++) {
                        styleValue.add(styles[i]);
                    }
                    img.attr("style",styleValue.toString());
                }
            }
            if (StringUtils.isBlank(width)){
                //7.43英寸  doc 1920
                width = img.attr("width").replaceAll("px","");
                if (Integer.parseInt(width) > 713 ){
                    img.attr("width","713px");
                }
            }
            result = doc.outerHtml();
        }
        return result;
    }


    public String docxToHtml(String sourceFileName, String targetFileName, String urlPre) throws Exception {
        File path = new File(ResourceUtils.getURL("classpath:").getPath());
        String imagePath = urlPre + "image";
        OutputStreamWriter outputStreamWriter = null;
        try {

            XWPFDocument document = new XWPFDocument(new FileInputStream(sourceFileName));
            XHTMLOptions options = XHTMLOptions.create();

            // 存放图片的文件夹
            options.setExtractor(new FileImageExtractor(new File(imagePath)));
            // html中图片的路径
            options.URIResolver(new BasicURIResolver("image"));
            outputStreamWriter = new OutputStreamWriter(new FileOutputStream(targetFileName), "UTF-8");
            XHTMLConverter xhtmlConverter = (XHTMLConverter) XHTMLConverter.getInstance();
            xhtmlConverter.convert(document, outputStreamWriter, options);
        } finally {
            if (outputStreamWriter != null) {
                outputStreamWriter.close();
            }
        }
        return "";
    }
    /**
     * 修改webword
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        WEBWORD wEBWORD = wEBWORDService.selectWEBWORDById(id);
        mmap.put("wEBWORD", wEBWORD);
        return prefix + "/edit";
    }

    /**
     * 修改保存webword
     */
    @RequiresPermissions("stock2:WEBWORD:edit")
    @Log(title = "webword", businessType = BusinessType.UPDATE)
    @PostMapping("/edit2")
    @ResponseBody
    public AjaxResult editSave2(String doc2html) {
        String os = System.getProperty("os.name");
        String urlPre = "/profile/upload/summernote-develop/doc2html/";
        if(os.toLowerCase().startsWith("win")){
            urlPre = "f:"+urlPre;
        }

        Document doc = Jsoup.parse(doc2html);
        Elements es = doc.getElementsByTag("title");
        String filename = es.get(0).html();
        File outputf = new File(urlPre + filename);
        FileOutputStream fos = null;
        OutputStreamWriter osw = null;
        try {
            fos = new FileOutputStream(outputf, false);
            osw = new OutputStreamWriter(fos, "utf-8");
            osw.write("<!DOCTYPE html>\n"+doc.html());
            return toAjax(1);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(osw !=null)
                    osw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return toAjax(0);

    }

    /**
     * 修改保存webword
     */
    @RequiresPermissions("stock2:WEBWORD:edit")
    @Log(title = "webword", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(WEBWORD wEBWORD)
    {
        return toAjax(wEBWORDService.updateWEBWORD(wEBWORD));
    }

    /**
     * 删除webword
     */
    @RequiresPermissions("stock2:WEBWORD:remove")
    @Log(title = "webword", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(wEBWORDService.deleteWEBWORDByIds(ids));
    }
}
